package com.jky.stmall.manger.service.impl;

import com.jky.stmall.manger.entity.Admin;
import com.jky.stmall.manger.mapper.AdminMapper;
import com.jky.stmall.manger.service.AdminService;
import com.jky.stmall.manger.util.MD5Util;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class AdminServiceImpl implements AdminService {
    /**
     * 提供一个有参的构造方法 不需要任何的注解
     * Spring4.x开始推荐使用构造方法注入
     */
    private AdminMapper adminMapper;

    @Override
    public Admin login(Admin admin) throws Exception {
        //1.参数的验证
        if (admin.getUsername()==null||admin.getUsername().length()<3||admin.getUsername().length()>16){
            throw new Exception("用户名必须是3~16位字符串");
        }
        if (admin.getPassword()==null ||admin.getPassword().length()<3||admin.getPassword().length()>16){
            throw new Exception("密码必须是3~16位字符串");
        }
        //根据用户名查询
        Admin sAdmin=adminMapper.selectByUsername(admin.getUsername());
        if (sAdmin==null){
            throw new Exception("用户名不存在！！！！");
        }
        //验证密码
        String password=admin.getPassword();
        password= MD5Util.getMD5(password+sAdmin.getSalt());
        //System.out.println(password);
        if(!password.equals(sAdmin.getPassword())){

            throw new Exception("密码错误！！！！");
        }
        if (sAdmin.getStatus()==1){
            throw new Exception("用户已被禁用！！！！");
        }
        //2.逻辑的处理

        //3.访问数据库
        return sAdmin;
    }

    @Override
    public Admin modifyPwd(Integer id, String oldPassword, String newPassword, String rePassword) throws Exception {
        //验证参数
        if (oldPassword==null || oldPassword.length()<3||oldPassword.length()>16){
            throw new Exception("旧密码格式不正确");
        }
        if (newPassword==null || newPassword.length()<3||newPassword.length()>16){
            throw new Exception("新密码格式不正确");
        }
        if (!newPassword.equals(rePassword)){
            throw  new Exception("两次密码不一致");
        }
        Admin admin=adminMapper.selectById(id);
        String md5Pwd=MD5Util.getMD5(oldPassword+admin.getSalt());
        if (!md5Pwd.equals(admin.getPassword())){
            throw  new Exception("旧密码不正确");
        }
        admin.setPassword(MD5Util.getMD5(newPassword+admin.getSalt()));
        adminMapper.update(admin);

        return admin;
    }

    @Override
    public Admin edit(Admin admin) throws Exception {
        if(admin.getId()==null){
            throw new Exception("ID不存在");
        }
        adminMapper.update(admin);
        return admin;
    }
}
